package com.hp.goods_service.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hp.common_api.entity.Goods;
import com.hp.common_api.entity.Spu;
import com.hp.common_api.entity.SpuDetail;
import com.hp.common_api.entity.Stock;
import com.hp.goods_service.config.RabbitMQConfig;
import com.hp.goods_service.mapper.SkuMapper;
import com.hp.goods_service.mapper.SpuDetailMapper;
import com.hp.goods_service.mapper.SpuMapper;
import com.hp.goods_service.mapper.StockMapper;
import com.hp.goods_service.service.ISpuService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * spu表，该表描述的是一个抽象性的商品，比如 iphone8 服务实现类
 * </p>
 *
 * @author xray
 * @since 2021-04-23
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements ISpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public IPage<Spu> getSpuPage(Page<Spu> page) {
        return spuMapper.selectSpuPage(page);
    }

    @Transactional
    @Override
    public void saveSpu(Goods goods) {
            Spu spu = goods.getSpu();
            //添加spu
            spuMapper.insertSpu(spu);
            //添加SpuDetail
            SpuDetail spuDetail = goods.getSpuDetail();
            spuDetail.setSpuId(spu.getId());
            spuDetailMapper.insert(spuDetail);
            //添加sku表
            goods.getSkus().forEach(sku -> {
                sku.setSpuId(spu.getId());
                skuMapper.insertSku(sku);
                //插入库存
                Stock stock = new Stock();
                stock.setSkuId(sku.getId());
                stock.setStock(sku.getStock());
                stockMapper.insert(stock);
            });
            //发送id给搜索服务进行数据同步
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_EXCHANGE,RabbitMQConfig.KEY_GOODS_SAVE,spu.getId());
    }
}
